import Vue from 'vue'
import VueRouter from 'vue-router'
// 静态路由数据
import constantRouterMap from './routes'

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import store from '@/store/index'
import util from '@/libs/util.js'

Vue.use(VueRouter)
//解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
//push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
	return originalPush.call(this, location).catch(err => err)
}
//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
	return originalReplace.call(this, location).catch(err => err)
}
// 导出路由 在 main.js 里使用
const router = new VueRouter({
	// mode: 'history',
	routes: constantRouterMap
})

const whiteList = ['/login']
let count = 0

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {

	// 进度条
	NProgress.start()

	if (whiteList.includes(to.path)) {
		// 在免登录白名单，直接进入
		next()
		NProgress.done()
	} else {
		if (count > 1000) {
			store.dispatch('d2admin/account/logout').then(r => {})
			NProgress.done()
			count = 0
			return
		}
		count++
		// 这里暂时将cookie里是否存有token作为验证是否登录的条件
		// 请根据自身业务需要修改
		const token = util.cookies.get('Mema-Token')
		const hasToken = token && token !== 'undefined'
		// 根据routers的值判断动态的菜单是否已经加载完成
		const isDynamicAddRoute = store.getters.permission.isDynamicAddRoute
		const menuList = util.session.get('menuList')
		console.log(hasToken);
		if (hasToken) {
			try {
				// 确认已经加载多标签页数据 https://github.com/d2-projects/d2-admin/issues/201
				await store.dispatch('d2admin/page/isLoaded')
				// 确认已经加载组件尺寸设置 https://github.com/d2-projects/d2-admin/issues/198
				await store.dispatch('d2admin/size/isLoaded')
				// 关闭搜索面板
				store.commit('d2admin/search/set', false)

				if (isDynamicAddRoute) {
					if (menuList && menuList.length > 0) {
						next()
						NProgress.done()
						count = 0
						return
					} else if (menuList.length === 0) {
						store.dispatch('d2admin/account/logout', {
								msg: '无任何菜单权限，请刷新页面或联系系统管理员'
							})
							.then(() => {})
						NProgress.done()
						count = 0
						return
					} else {
						store.commit('d2admin/permission/SET_ISLOCK', false)
					}
				}
				// 已经登录，根据后台返回菜单生成路由
				await store.dispatch('d2admin/permission/generateRoutes').then(() => {
					const redirect = decodeURIComponent(from.query.redirect || to.path)
					console.log(to.path);
					console.log(redirect);
					if (to.path === redirect||to.path === '/index') {
						// hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
						next({
							...to,
							replace: true
						})
					} else {
						// 跳转到目的路由
						console.log('跳转到目的路由');
						next({
							path: redirect
						})
						NProgress.done()
					}
				}).catch(err => {
					console.log('111catch');
					next({
						path: '/login'
					})
					NProgress.done()
					count = 0
				})
			} catch (err) {
				next({
					path: '/login'
				})
				NProgress.done()
				count = 0
			}
		} else {
			console.log('===没有token跳登录页===');
			// 没有登录的时候跳转到登录界面
			next({
				path: '/login'
			})
			NProgress.done()
			count = 0
		}
	}
})

router.afterEach(to => {
	// 进度条
	NProgress.done()
	// 多页控制 打开新的页面
	store.dispatch('d2admin/page/open', to).then(() => {})
	// 更改标题
	util.title(to.meta.title)
})

export default router